const { add, getAll, getOne, update, remove } = require('../utils/dbTools')
const { getMemberInfoById, updateMember } = require('./member')


const tableName = 'business_invite'

/**
 * 获取邀请列表数据
 * @param {object} map 查询条件  {page:'页码',size:'每页显示数据条目',invited_uid:'受邀方uid'}
 * 
*/
const getInviteList = async (map) => {
    const result = await getAll(tableName, map)
    return result
}

/**
 * 获取邀请详情数据
 * @param {object} map 查询条件  {id:'邀请id'}
 * 
*/
const getInviteInfo = async (map) => {
    const result = await getOne(tableName, map)
    return result
}

/**
 * 更新邀请数据
 * @param {number} id 邀请id
 * @parem {number} invite_status 邀请状态 2-接受邀请, 3-拒绝邀请
 * 
*/
const updateInvite = async (id, invite_status) => {
    if (!id || !invite_status) { return false }
    // 获取邀请详情数据
    const { invited_uid, bus_id } = await getInviteInfo({ id })
    if (!invited_uid || !bus_id) {
        return false
    }
    const fields = { invite_status }
    // 更新邀请信息
    const result = await update({ id }, fields, tableName)
    // 如果接受邀请,更新受邀账号信息
    if (invite_status === 2) {
        await updateMember(invited_uid, { account_type: 2, bus_id })
    }
    return result
}


/**
 * 新增企业加入邀请数据
 * @param {number} invite_uid 邀请发出方账号id
 * @param {number} invited_uid 受邀方账号id
 * 
*/
const addInvite = async (invite_uid, invited_uid) => {
    if (!invite_uid || !invited_uid) { return false }
    // 查询企业id
    const { bus_id } = await getMemberInfoById(invite_uid)
    const fields = { bus_id, invite_uid, invited_uid }
    const result = await add(fields, tableName)
    return result
}


/**
 * 删除邀请数据
 * @param {number} id 邀请id
 * 
*/
const removeInvite = async (id) => {
    if (!id) { return false }
    const result = await remove(id, tableName)
    return result
}

module.exports = {
    addInvite,
    getInviteList,
    getInviteInfo,
    updateInvite,
    removeInvite
}